package com.otitan.forest.right.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.otitan.forest.right.dto.LoginDto;
import com.otitan.forest.right.dto.SysUserDto;
import com.otitan.forest.right.dto.UpdatePwdDto;
import com.otitan.forest.right.entity.SysOrganizationEntity;
import com.otitan.forest.right.entity.SysRoleEntity;
import com.otitan.forest.right.entity.SysUserEntity;
import com.otitan.forest.right.entity.SysUserRoleRelationEntity;
import com.otitan.forest.right.service.SysOrganizationService;
import com.otitan.forest.right.service.SysRoleService;
import com.otitan.forest.right.service.SysUserRoleRelationService;
import com.otitan.forest.right.service.SysUserService;
import com.otitan.forest.right.util.CommonUtil;
import com.otitan.webapp.framework.basepro.exception.BusinessException;
import com.otitan.webapp.framework.basepro.model.DataResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * 用户
 *
 * @author xiazw
 * @email *****@mail.com
 * @date 2020-08-04 14:19:45
 */
@Api(tags = "用户API")
@RestController
@RequestMapping("/sysUser")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleRelationService sysUserRoleRelationService;

    @Autowired
    private SysOrganizationService sysOrganizationService;


    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public DataResult login(@RequestBody SysUserEntity sysUser) {
        return sysUserService.login(sysUser);
    }

    @ApiOperation(value = "智慧林业系统登录")
    @PostMapping("/zhly/login")
    public DataResult zhlyLogin(@RequestBody LoginDto dto) {
        return sysUserService.zhlyLogin(dto);
    }

    @ApiOperation(value = "用户注销")
    @PostMapping(value = "/userlogout")
    public DataResult userLogout() {
        SecurityUtils.getSubject().logout();
        return DataResult.success();
    }

    @RequiresRoles(value = {"admin", "ordinary", "audit"}, logical = Logical.OR)
    @ApiOperation(value = "获取当前登录用户")
    @GetMapping("/getCurrentUser")
    public DataResult getCurrentUser(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("Authorization");
        SysUserDto userDto = null;
        SessionKey key = new WebSessionKey(token, request, response);
        try {
            Session se = SecurityUtils.getSecurityManager().getSession(key);
            Object obj = se.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            //org.apache.shiro.subject.SimplePrincipalCollection cannot be cast to com.hncxhd.bywl.entity.manual.UserInfo
            SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
            SysUserEntity user = (SysUserEntity) coll.getPrimaryPrincipal();
            userDto = CommonUtil.copy(user, SysUserDto.class);
            List<SysRoleEntity> roleList = sysRoleService.findRoleByUserId(user.getId());
            userDto.setRoleEntities(roleList);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
       /* SessionKey key = new WebSessionKey(token, request, response);
        SysUserEntity sessionUserBean = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();*/

        return DataResult.success(userDto);
    }

    @RequiresRoles(value = {"admin"}, logical = Logical.OR)
    @ApiOperation(value = "新增")
    @PostMapping("/add")
    public DataResult add(@RequestBody SysUserDto sysUserDto) {
        SysUserEntity sysUser = CommonUtil.copy(sysUserDto, SysUserEntity.class);
        sysUser.setProvince("520000");

        //给密码进行包装加密
        SysUserEntity user = sysUserService.packagePassword(sysUser);
        String groupId = user.getGroupId();

        // 查询用户所属行政区级别
        SysOrganizationEntity orgInfo = sysOrganizationService.getById(groupId);
        user.setBelongGroupLevel(orgInfo.getLevel());
        sysUserService.save(user);

        LambdaQueryWrapper<SysUserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUserEntity::getUsername, sysUser.getUsername());
        SysUserEntity sysUserEntity = sysUserService.getOne(queryWrapper);
        List<SysRoleEntity> role = sysUserDto.getRoleEntities();
        if (role != null && role.size() > 0) {
            //sysUserRoleRelationService.insertByUserIdAndRoleId(sysUserDto.getId(), role);
            for (SysRoleEntity sysRoleEntity : role) {
                SysUserRoleRelationEntity sysUserRoleRelationEntity = new SysUserRoleRelationEntity(sysUserEntity.getId(), sysRoleEntity.getId());
                sysUserRoleRelationService.save(sysUserRoleRelationEntity);
            }
        }
        return DataResult.success();
    }

    @RequiresRoles(value = {"admin"}, logical = Logical.OR)
    @ApiOperation(value = "删除")
    @DeleteMapping("/delete")
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
        sysUserService.removeByIds(ids);
        return DataResult.success();
    }

    @RequiresRoles("admin")
    @ApiOperation(value = "更新")
    @PutMapping("/update")
    public DataResult update(@RequestBody SysUserDto sysUserDto) {
        SysUserEntity sysUser = CommonUtil.copy(sysUserDto, SysUserEntity.class);
        sysUserService.checkUpdateUser(sysUser);

        // 查询用户所属行政区级别
        SysOrganizationEntity orgInfo = sysOrganizationService.getById(sysUser.getGroupId());
        sysUser.setBelongGroupLevel(orgInfo.getLevel());

        sysUserService.updateById(sysUser);
        List<SysRoleEntity> role = sysUserDto.getRoleEntities();
        if (role != null && role.size() > 0) {
            sysUserRoleRelationService.updateByUserIdAndRoleId(sysUserDto.getId(), role);
        }
        return DataResult.success();
    }

    @ApiOperation(value = "查询分页数据")
    @RequiresRoles(value = {"admin", "ordinary", "audit"}, logical = Logical.OR)
    @PostMapping("/listByPage")
    public DataResult findListByPage(@RequestBody SysUserEntity sysUser) {
        Page page = new Page(sysUser.getPage(), sysUser.getSize());
        LambdaQueryWrapper<SysUserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.orderByDesc(SysUserEntity::getCreateDate);
        //查询条件示例
        //queryWrapper.eq(SysUserEntity::getId, sysUser.getId());
        queryWrapper.ne(SysUserEntity::getUsername, "admin");

        Integer belongGroupLevel = sysUser.getBelongGroupLevel();

        if (StringUtils.isNotEmpty(sysUser.getPhone())) {
            queryWrapper.like(SysUserEntity::getPhone, sysUser.getPhone());
        }
        if (StringUtils.isNotEmpty(sysUser.getRealName())) {
            queryWrapper.like(SysUserEntity::getRealName, sysUser.getRealName());
        }

        if (belongGroupLevel != null) {
            String groupId = sysUser.getGroupId();
            queryWrapper.likeRight(SysUserEntity::getGroupId, groupId.substring(0, belongGroupLevel * 2));
        } else {
            if (StringUtils.isNotEmpty(sysUser.getGroupId())) {
                List<String> ids = sysOrganizationService.getGroupId(sysUser.getGroupId());
                queryWrapper.in(SysUserEntity::getGroupId, ids);
            }
        }

        IPage<SysUserEntity> iPage = sysUserService.page(page, queryWrapper);
        return DataResult.success(iPage);
    }

    @RequiresRoles(value = {"admin", "ordinary", "audit"}, logical = Logical.OR)
    @ApiOperation(value = "根据Id查询实体")
    @GetMapping("/findOne/{id}")
    public DataResult findOneById(@PathVariable String id) {
        SysUserEntity entityObj = sysUserService.getById(id);
        SysUserDto sysUserDto = CommonUtil.copy(entityObj, SysUserDto.class);
        sysUserDto.setRoleEntities(sysRoleService.findRoleByUserId(id));
        return DataResult.success(sysUserDto);
    }

    /**
     * 从智慧林业系统查询用户信息 《慎用》
     *
     * @param [uuid]
     * @return com.otitan.webapp.framework.basepro.model.DataResult
     * @throws
     * @author jiachangsen
     * @date 2020/08/21 15:13
     */
    @ApiOperation(value = "从智慧林业系统查询用户信息", hidden = true)
    @GetMapping("/dataSynchronization")
    @RequiresRoles(value = {"admin"})
    public DataResult dataSynchronization(String uuid) {
        return sysUserService.dataSynchronization(uuid);
    }


    @ApiOperation(value = "修改密码")
    @PostMapping("/updatePwd")
    public DataResult updatePwd(@RequestBody UpdatePwdDto updatePwdDto) {
        return sysUserService.updatePwdByUsername(updatePwdDto);
    }


}
